import React from 'react'
import './index.css'

import MUtil from 'util/mm.jsx'
const __mm=new MUtil();

import User from 'service/user-service.jsx'
const __user=new User();

class Login extends React.Component{
    constructor(props){
        super(props);
        this.state={
            username:'',
            password:'',
            redirect:__mm.getUrlParam('redirect') || ''
        }
    }
    componentWillMount(){
        document.title='登录';
    }
    onInputChange(e){
        let inputValue  = e.target.value,
            inputName   = e.target.name;
        this.setState({
            [inputName] : inputValue
        });
    }
    onInputKeyUp(e){
        if(e.keyCode===13){
            this.onSubmit(e);
        }
    }
    onSubmit(e){
        let loginInfo={
            username:this.state.username,
            password:this.state.password
        },
       checkResult= __user.checkLoginInfo(loginInfo);
        if(checkResult.status){
            __user.login(loginInfo).then(res=>{
                __mm.setStorage('userInfo',res);
                this.props.history.push(this.state.redirect);
            },errmsg=>{
                __mm.errorTips(errmsg);
            })
        }else{
            __mm.errorTips(checkResult.msg);
        }


    }
    render(){
        return (
                <div className='col-md-4 col-md-offset-4'>
                    <div className="panel panel-default login-panel">
                        <div className="panel-heading">欢迎登录</div>
                        <div className="panel-body">
                            <div>
                                <div className="form-group">
                                    <label htmlFor="exampleInputEmail1">用户名</label>
                                    <input type="text" name="username" className="form-control" id="exampleInputEmail1" placeholder="请输入用户名"
                                    onChange={e=>this.onInputChange(e)}
                                    onKeyUp={e=>this.onInputKeyUp(e)} />
                                </div>
                                <div className="form-group">
                                    <label htmlFor="exampleInputPassword1">密码</label>
                                    <input type="password" name="password"  className="form-control" id="exampleInputPassword1" placeholder="请输入密码"
                                    onChange={e=>this.onInputChange(e)}
                                    onKeyUp={e=>this.onInputKeyUp(e)} />
                                </div>
                                <button className="btn btn-primary btn-block" onClick={e=>this.onSubmit(e)}>登录</button>
                            </div>
                        </div>
                    </div>
                </div>

        )
    }
}
export default Login;